package com.fzy.common.tree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 树形菜单工具类
 *
 * @author 冯赵杨
 * @create 2018/9/27
 */
public class TreeUtil {

    /**
     * for循环构造树形结构
     *
     * @param list
     * @return
     * @author 冯赵杨
     */
    public static List<TreeNode> listToTreeList(List<? extends TreeNode> list) {
        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }
        List<Integer> childId = new ArrayList<>();
        for (TreeNode treeNode : list) {
            childId.add(treeNode.getId());
        }
        List<TreeNode> treeList = new ArrayList<>();
        for (TreeNode tree : list) {
            //找到根
            if (!childId.contains(tree.getPid())) {
                treeList.add(tree);
            }
            //找到子
            for (TreeNode treeNode : list) {
                if (treeNode.getPid() == tree.getId()) {
                    if (tree.getChildren() == null) {
                        tree.setChildren(new ArrayList<>());
                    }
                    tree.getChildren().add(treeNode);
                }
            }
        }
        return treeList;
    }


    /**
     * 递归构造树形结构集合
     *
     * @param list
     * @return
     * @author 冯赵杨
     * @create 2018/9/6
     */
    public static List<TreeNode> getTreeList(List<TreeNode> list) {
        return getChildList(0, list);
    }

    /**
     * 根据id和pid进行递归获取下级树节点
     *
     * @param pid
     * @param list
     * @return
     * @author 冯赵杨
     * @create 2018/9/6
     */
    public static List<TreeNode> getChildList(int pid, List<TreeNode> list) {
        List<TreeNode> childList = new ArrayList<>();
        for (TreeNode item : list) {
            if (pid == item.getPid()) {
                List<TreeNode> childMenuList = getChildList(item.getId(), list);
                item.setChildren(childMenuList);
                childList.add(item);
            }
        }
        return childList;
    }

}
